/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2025-01-04 19:38:11
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2025-03-07 15:28:27
 * @FilePath: \project-my\vue-mall\vite.config.ts
 * @Description: 
 */
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { gzipSync } from 'zlib' //gizp 压缩
import { brotliCompressSync } from 'zlib' //brotli 压缩
// icon自动导入
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'

import sassDts from 'vite-plugin-sass-dts';

// https://vitejs.dev/config/
export default defineConfig(() => {
  return {
    plugins: [
      vue(),
      AutoImport({
        resolvers: [
          ElementPlusResolver(),
          IconsResolver({
            prefix: 'Icon',
          })
        ],
      }),
      Components({
        resolvers: [
          ElementPlusResolver(),
          IconsResolver({
            enabledCollections: ['ep'],
          })
        ],
        // 配置elementPlus采用sass样式配色系统
        // ElementPlusResolver({ importStyle:"sass"})，
      }),
      Icons({
        autoInstall: true,
      }),
      sassDts()
    ],
    resolve: {
      alias: {
        "~": path.resolve(__dirname, "./"),
        "@": path.resolve(__dirname, "./src")
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          silenceDeprecations: ['legacy-js-api'],
          // api: 'modern-compiler'
          // api: 'legacy'
        }
      }
    },
    // css: {
    //   preprocessorOptions: {
    //     scss: { // scss 公共样式引入
    //       // additionalData: `@import "@/assets/css/theme.scss"`,
    //       // additionalData: `@import "~normalize.css/normalize.scss";`
    //       api:'modern'
    //     }
    //   }
    // },
    // base: env.mode === 'devlop' ? '' : 'production',
    server: {
      host: '0.0.0.0', // 监听所有ip
      port: 3000, // 端口号
      proxy: {
        '/api': {
          target: 'http://localhost:3008',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    build: {
      cssCodeSplit: true,
      chunkSizeWarningLimit: 2000,
      assetsInlineLimit: 4000,
      sourcemap: false,
      minify: 'terser', // 代码混淆
      assetsDir: 'static/assets',
      // 在生产环境移除console.log
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      // 静态资源打包到dist下的不同目录
      // rollupOptions: {
      //   output: {
      //     chunkFileNames: 'static/js/[name]-[hash].js',
      //     entryFileNames: 'static/js/[name]-[hash].js',
      //     assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
      //   },
      // }
      rollupOptions: {
        output: {
          // 将第三方所有依赖打包成各自命名的单独文件
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          },
          plugins: [
            // 还需要nginx配置
            // # ... existing code ...
            // http {
            //     # ... existing code ...
            //     gzip on;
            //     gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
            //     gzip_vary on;

            //     # Brotli settings
            //     brotli on;
            //     brotli_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
            //     brotli_comp_level 6;

            //     # ... existing code ...
            //     server {
            //         # ... existing code ...
            //         location / {
            //             # ... existing code ...
            //         }
            //     }
            // }
            {
              name: 'compress-gzip', // gizp 压缩配置
              generateBundle(options, bundle) {
                for (const [name, asset] of Object.entries(bundle)) {
                  if (asset.type === 'asset') {
                    const compressed = gzipSync(asset.source)
                    this.emitFile({
                      type: 'asset',
                      fileName: `${name}.gz`,
                      source: compressed,
                    })
                  }
                }
              },
            },
            // {
            //   name: 'compress-brotli', // brotli 压缩配置
            //   generateBundle(options, bundle) {
            //     for (const [name, asset] of Object.entries(bundle)) {
            //       if (asset.type === 'asset') {
            //         const compressed = brotliCompressSync(asset.source)
            //         this.emitFile({
            //           type: 'asset',
            //           fileName: `${name}.br`,
            //           source: compressed,
            //         })
            //       }
            //     }
            //   },
            // },
          ],
        },
      },
    }
  }
})
